
const resultDiv = document.getElementById('result');
const historyDiv = document.getElementById('history');
const exportBtn = document.getElementById('export-btn');
const clearBtn = document.getElementById('clear-btn');

// 计算碳排放的函数（假设你有一个函数来计算碳排放）
function calculateCarbon() {
    // 这里应该是你的计算逻辑，以下为示例值
    const distance = parseFloat(document.getElementById('distance').value);
    const publicTransport = parseFloat(document.getElementById('publicTransport').value);
    const meatConsumption = parseFloat(document.getElementById('meatConsumption').value);
  
    // 假设的系数
    const distanceFactor = 0.2; // 每公里产生的碳排放量
    const publicTransportFactor = -0.1; // 每次使用公共交通减少的碳排放量
    const meatFactor = 2.3; // 每公斤肉类产生的碳排放量
  
    // 计算碳排放
    const carbonEmission = (distance * distanceFactor) 
                         + (publicTransport * publicTransportFactor) 
                         + (meatConsumption * meatFactor);
  
    // 显示结果
    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = `<strong>您的碳排放量约为：${carbonEmission.toFixed(2)} kg CO2</strong>`;
  
    // 保存结果
    // saveResult(carbonEmission);
    displayResult(carbonEmission);
    saveToLocalStorage({ date: new Date().toLocaleString(), carbon: carbonEmission });
}

// 显示当前计算结果
function displayResult(result) {
    resultDiv.innerHTML = `<p>当前计算结果: ${result} kg CO2</p>`;
}

// 存储和检索历史记录
function saveToLocalStorage(result) {
    let history = JSON.parse(localStorage.getItem('carbonHistory')) || [];
    history.push(result);
    localStorage.setItem('carbonHistory', JSON.stringify(history));
    displayHistory();
}

// 显示历史记录
function displayHistory() {
    let history = JSON.parse(localStorage.getItem('carbonHistory')) || [];
    let historyHtml = '<ul>';
    history.forEach((entry, index) => {
        historyHtml += `<li>${entry.date}:${entry.carbon} kg CO2</li>`;
    });
    historyHtml += '</ul>';
    historyDiv.innerHTML = historyHtml;
}

// 清除历史记录
function clearHistory() {
    history = [];
    localStorage.removeItem('carbonHistory');
    displayHistory();
}

// 绑定清楚按钮点击事件
clearBtn.addEventListener('click', function() {
    clearHistory();
});

// 导出JSON数据为CSV文件
function exportToJsonFile(jsonData) {
    if (!jsonData || jsonData.length === 0) {
        alert('没有数据可以导出！');
        return;
    }

    let csvContent = "data:text/csv;charset=utf-8,";
    csvContent += "Date,Carbon (kg CO2)\n"; // CSV header

    jsonData.forEach(function(rowArray) {
        let row = rowArray.date + "," + rowArray.carbon;
        csvContent += row + "\r\n";
    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "carbon_emissions.csv");
    document.body.appendChild(link); // Required for FF

    link.click(); // This will download the CSV file
}

// 绑定导出按钮点击事件
exportBtn.addEventListener('click', function() {
    let jsonData = JSON.parse(localStorage.getItem('carbonHistory')) || [];
    exportToJsonFile(jsonData);
});

// 在页面加载时显示历史记录
window.onload = function() {
    displayHistory();
};

// 绑定计算按钮点击事件（假设有一个ID为'calculate-btn'的按钮）
document.getElementById('calculate-btn').addEventListener('click', calculateCarbon);


// =============================================================================
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('carbonForm');
    const historyList = document.getElementById('historyList');
    const clearHistoryBtn = document.getElementById('clearHistoryBtn');
    const saveHistoryBtn = document.getElementById('saveHistoryBtn');

    // 初始化历史记录
    let history = JSON.parse(localStorage.getItem('carbonHistory')) || [];

    // 显示历史记录
    function displayHistory() {
        historyList.innerHTML = '';
        history.forEach(function(record) {
            const li = document.createElement('li');
            li.textContent = record; // 假设record是一个字符串
            historyList.appendChild(li);
        });
    }

    // 保存历史记录到本地存储
    function saveHistory() {
        localStorage.setItem('carbonHistory', JSON.stringify(history));
    }

    // 清除历史记录
    function clearHistory() {
        history = [];
        localStorage.removeItem('carbonHistory');
        displayHistory();
    }

    // 这里应该是你的计算逻辑，以下为示例值
    function calculateCarbon() {
    
        const distance = parseFloat(document.getElementById('distance').value);
        const publicTransport = parseFloat(document.getElementById('publicTransport').value);
        const meatConsumption = parseFloat(document.getElementById('meatConsumption').value);
      
        // 假设的系数
        const distanceFactor = 0.2; // 每公里产生的碳排放量
        const publicTransportFactor = -0.1; // 每次使用公共交通减少的碳排放量
        const meatFactor = 2.3; // 每公斤肉类产生的碳排放量
      
        // 计算碳排放
        const carbonEmission = (distance * distanceFactor) 
                             + (publicTransport * publicTransportFactor) 
                             + (meatConsumption * meatFactor);
      
        // 显示结果
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML = `<strong>您的碳排放量约为：${carbonEmission.toFixed(2)} kg CO2</strong>`;
      
        // 保存结果
        // saveResult(carbonEmission);
        displayResult(carbonEmission);
        saveToLocalStorage({ date: new Date().toLocaleString(), carbon: carbonEmission });
    }

    // 表单提交处理
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        // 假设这里计算出了result
        calculateCarbon();
        const result = carbonEmission //'计算结果'; // 替换为实际的计算结果
        history.unshift(result); // 逆序保存
        displayHistory();
        saveHistory();
    });

    // 绑定清除历史记录按钮
    clearHistoryBtn.addEventListener('click', clearHistory);

    // 绑定保存历史记录按钮（在这个例子中，每次提交都会保存，所以这个按钮可能不需要）
    saveHistoryBtn.addEventListener('click', saveHistory);

    // 页面加载时显示历史记录
    displayHistory();
});
